import * as mqtt from 'mqtt/dist/mqtt.min';
import AESUtils from '@/utils/AES.js'
import mitt from 'mitt'
export const emitter = mitt()
// let willTopic = makeTopic({ address:s,name:'offline', type:1, })
import { vddsim_protocol, vddsim_port, vddsim_host, vddsim_endpoint, username, password, vddtt_message_password, groupContract, chainId } from '@/utils/config.js'
import store from '../../store';
export function makeTopic({ address, name, type }) {
    let back = name || '#'
    let first = `chat/private`
    let contract = groupContract.toLowerCase()
    if (type == 1) {
        first = 'member'
    }else if(type==2){
        first ='chat/group'
    }
    return `${first}/${contract}-${chainId}/${address}/${back}`
}
const options = {
    protocol: vddsim_protocol,
    host: vddsim_host,
    port: vddsim_port,
    endpoint: vddsim_endpoint,
    clean: true, // 保留会话
    // 认证信息
    clientId: '',
    username: username, //用户名 不用的话什么也不用填
    password: password, //密码 不用的话什么也不用填
    keepalive: 10,
    keepAliveInterval: 4, //心跳包
    timeout: 6, //超时时间
    reconnect: true, //自动重连
    // will: {
    //   topic: willTopic,
    //   payload: 'Connection Closed abnormally..!',
    //   retain: false,
    //   qos: 0,
    // },
};
const id = chainId + '_' + parseInt(Math.random() * 1000000)
options.clientId = id;
let url = options.protocol + '://' + options.host + ':' + options.port + options.endpoint
export const mqttClient = mqtt.connect(url, options);
mqttClient.on('error', error => {
    console.log('连接错误', error);
});
mqttClient.on('disconnect', error => {
    console.log('断开连接');
})
mqttClient.on('reconnect', () => {
    console.log('重新连接');
});
mqttClient.on('close', () => {
    console.log('关闭连接');
});
mqttClient.on('message', (topic, message) => {
  if (topic.indexOf('member') > -1) {
    messageCallback(topic, vddsimObj.state)
    return
  }
  try {
    var content = message.toString()
    var content1 = AESUtils.decrypt(content, vddtt_message_password)
    var messageObj = JSON.parse(content1)
    console.log(messageObj)
    // if (messageObj.c != vddsimObj.address.toLowerCase()) {
    //   //接收到的对方的消息
      store.getMessage(topic, messageObj)
    // }
  } catch (e) {

  }
  emitter.emit(topic, messageObj)
})
export function subscribe(topic,type) {
    let topicName = ''
    if(topic instanceof Array ){
        let arrTopic = []
        topic.forEach(res=>{
            arrTopic.push(makeTopic({ address:res, type }))
        })
        topicName = arrTopic
    }else{
         topicName = makeTopic({ address:topic, type })
    }
  mqttClient.subscribe(topicName, {qos: 0}, (err) => {
    if (!err) {
      console.log(`订阅主题 ${topicName} 成功`)
    }
  })
}
/**
 *
 * @param topic 订阅的topic
 * @param callbackFunction 接收到指定的topic消息之后的回调
 */
export function onMqttMessage({topic, cb}) {
  // mitt监听指定topic
  emitter.on(topic, cb)
  // 已建立mqtt链接
  if (mqttClient.connected) {
    subscribe(topic)
  } else {
    // 如果还没有连接成功，就监听连接，确保订阅一定能成功
    mqttClient.on('connect', () => {
      console.log(`mqtt：${process.env.VUE_APP_MQTT}  连接成功...`)
      // 连接成功之后再订阅
      subscribe(topic)
    })
  }
}

// 取消订阅
export function unsubscribe(topic) {
  emitter.off(topic)
  mqttClient.unsubscribe(topic, {}, (err) => {
    if (!err) {
      console.log(`取消订阅${topic}成功`)
    }
  })
}
	//发送
export	function sendMessage(payload, to, callback, name, type) {
		let content = AESUtils.encrypt(JSON.stringify(payload), vddtt_message_password)
		let lastName = name || 'send'
		const topicName = makeTopic({ address: to, name: lastName, type })
		const qos = 0;
		if (!mqttClient.connected) {
			mqttClient.on('connect', () => {
				try {
					console.log('发送成功', topicName, payload)
					if (mqttClient.connected) {
						mqttClient.publish(topicName, content, {
							qos
						}, (error) => {
							if (error) {
								callback(0)
							} else {
								callback(payload, to)
							}
						})
					} else {
						callback(0)
					}
				} catch (error) {

				}
			})
		} else {
			if (mqttClient.connected) {
				mqttClient.publish(topicName, content, {
					qos
				}, (error) => {
					try {
						if (error) {
							callback(0)
						} else {
							callback(payload, to)
						}
					} catch (error) {

					}

				})
			} else {
				callback(0)
			}
		}
	}

// mqtt自检重连，间隔10秒检测一次，连续检测3次都是断连状态则手动进行链接
export function mqttReconnect() {
  let count = 0
  // 每隔10秒检测mqtt是否断连，如果断连了，重新链接
  setInterval(() => {
    // 如果还没创建好客户端
    if (!mqttClient) {
      return;
    }
    // 如果已连接
    if (mqttClient.connected) {
      count = 0
      return
    }
    // mqtt没有连接成功
    count++
    if (count >= 3) {
      mqttClient.reconnect()
      count = 0
    }
  }, 10 * 1000)
}

// 启动mqtt自检重连服务
mqttReconnect()